//
//  PostViewController.swift
//  MT
//
//  Created by M on 2019/12/26.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import GrowingTextView

class PublishViewController: BaseViewController {
    
    private static var maxTextCount: Int {
        return 140
    }
    
    /// 发布按钮
    var postButton: UIButton?
    
    /// 可选模型
    var assets: [MTAsset]?
    /// 已选模型
    private var selectedAssets: [MTAsset] = []
    /// 是否选择到最大数量 - 是否不能再选
    private var photoLibrarySelectable: Bool {
        return selectedAssets.count == 9 || (selectedAssets.first?.mediaType == .video)
    }
    /// 所有视频是否可选
    private var isAllVideoEnabled: Bool = true
    /// 定位
    private var location: String?
    
    lazy var textView: GrowingTextView = {
        let textView = GrowingTextView()
        textView.delegate = self
        textView.textColor = .white
        textView.backgroundColor = UIColor.common.x161616
        textView.frame = CGRect(x: 16, y: 0, width: ScreenWidth - 32, height: 200)
        textView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
        textView.placeholder = "分享你的精彩时刻..."
        textView.font = PingFangSCRegularFont(14)
        textView.maxLength = 140
        textView.maxHeight = 300
        textView.tintColor = .white
        //textView.keyboardAppearance = .dark
        
        let tool = UIToolbar(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 40))
        tool.barStyle = .black
        
        let spacing = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        btn.setTitle("完成", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(postViewController(didClickToolBarDoneButton:)), for: .touchUpInside)
        let item1 = UIBarButtonItem(customView: btn)
        tool.items = [spacing, item1]
        textView.inputAccessoryView = tool
        
        return textView
    }()
    
    /// 字数 Label
    lazy var textCountLabel: UILabel = {
        let label = UILabel()
        label.text = "0/\(PublishViewController.maxTextCount)"
        label.font = PingFangSCRegularFont(12)
        label.textColor = .white
        label.textAlignment = .right
        return label
    }()
    
    /// 已选图片 CollectionView
    lazy var selectedAssetCollectionView: UICollectionView = {
        let leftRightInset: CGFloat = 15.0
        let spacing: CGFloat = 10.0
        let count: CGFloat = 5.0
        let wh = (ScreenWidth - (leftRightInset * 2) - (spacing * (count - 1))) / count
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: wh, height: wh)
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = spacing
        flowLayout.minimumInteritemSpacing = spacing
        let cv = UICollectionView(frame: CGRect(x: 0, y: textView.frame.maxY + 50, width: ScreenWidth, height: wh), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.common.x161616
        cv.delegate = self
        cv.dataSource = self
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        cv.contentInset = UIEdgeInsets(top: 0, left: leftRightInset, bottom: 0, right: leftRightInset)
        cv.register(PublishAddAssetCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: PublishAddAssetCollectionViewCell.self))
        cv.register(PhotoLibarayCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: PhotoLibarayCollectionViewCell.self))
        return cv
    }()
    
    /// 展示相册 collectionView
    lazy var photoLibraryCollectionView: UICollectionView = {
        let leftRightInset: CGFloat = 18.0
        let spacing: CGFloat = 7.0
        let count: CGFloat = 4.0
        let wh = (ScreenWidth - (leftRightInset * 2) - (spacing * (count - 1))) / count
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: wh, height: wh)
        flowLayout.minimumLineSpacing = spacing
        flowLayout.minimumInteritemSpacing = spacing
        let cv = UICollectionView(frame: CGRect(x: 0, y: selectedAssetCollectionView.frame.maxY + 10, width: ScreenWidth, height: self.view.frame.height - selectedAssetCollectionView.frame.maxY), collectionViewLayout: flowLayout)
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = UIColor.common.x161616
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        cv.contentInset = UIEdgeInsets(top: 0, left: leftRightInset, bottom: ScreenBottomExtraOffset, right: leftRightInset)
        cv.keyboardDismissMode = .onDrag
        cv.register(PhotoLibrarySelectableCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: PhotoLibrarySelectableCollectionViewCell.self))
        return cv
    }()

}

// MARK: ------------------ Overrides ----------------------
extension PublishViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        fetchAssets()
        initializeUI()
    }
    
}


// MARK: ------------------ 初始化 ----------------------
extension PublishViewController {
    
    private func setup() {
        let l_btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        l_btn.setImage(UIImage(named: "icon_dismiss"), for: .normal)
        l_btn.adjustsImageWhenHighlighted = false
        l_btn.addTarget(self, action: #selector(postViewController(didClickDismissButton:)), for: .touchUpInside)
        let leftButton = UIBarButtonItem(customView: l_btn)
        self.navigationItem.leftBarButtonItem = leftButton
        
        let r_btn = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
        r_btn.setBackgroundImage(UIImage(color: UIColor(hex: 0x5d5d5d)), for: .disabled)
        r_btn.setBackgroundImage(UIImage(color: UIColor.theme.main), for: .normal)
        r_btn.setTitle("发布", for: .normal)
        r_btn.setTitleColor(.black, for: .normal)
        r_btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        r_btn.adjustsImageWhenHighlighted = false
        r_btn.layer.cornerRadius = 3
        r_btn.clipsToBounds = true
        r_btn.addTarget(self, action: #selector(postViewController(didClickPostButton:)), for: .touchUpInside)
        self.postButton = r_btn
        let rightButton = UIBarButtonItem(customView: r_btn)
        rightButton.isEnabled = false
        self.navigationItem.rightBarButtonItem = rightButton
    }
    
    private func fetchAssets() {
        MTAssetLibrary.request { (flag) in
            DispatchQueue.main.async {
                if flag {
                    MTAssetLibrary.default.requestForCameraRollAlbum { [weak self] (cameraRollAlbum) in
                        guard let weakSelf = self else { return }
                        weakSelf.assets = cameraRollAlbum.assets
                        weakSelf.photoLibraryCollectionView.reloadData()
                    }
                } else {
                    AlertManager.presentAlertView(message: "请在设置开启相册权限")
                }
            }
        }
    }
    
    private func initializeUI() {
        view.backgroundColor = UIColor.common.x161616
        view.addSubview(textView)
        view.addSubview(textCountLabel)
        view.addSubview(selectedAssetCollectionView)
        view.addSubview(photoLibraryCollectionView)
        
        textCountLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView.snp.bottom).offset(10)
            make.right.equalTo(view).offset(-16)
        }
        
    }
    
}


// MARK: ------------------ 事件方法 ----------------------
@objc
extension PublishViewController {
    
    private func postViewController(didClickDismissButton sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
    
    private func postViewController(didClickPostButton sender: UIButton) {
        self.publish()
        self.dismiss(animated: true) {
            self.navigationVC?.selectHome()
        }
    }
    
    private func postViewController(didTapView gestureRecognizer: UITapGestureRecognizer) {
        if textView.isFirstResponder {
            textView.resignFirstResponder()
        }
    }
    
    private func postViewController(didClickToolBarDoneButton sender: UIBarButtonItem) {
        if textView.isFirstResponder {
            textView.resignFirstResponder()
        }
    }
    
}

// MARK: ------------------ 相册选择逻辑 / 发布状态 ----------------------
extension PublishViewController {
    
    /// 设置是否禁止所有视频选择
    private func setAllVideoEnabled(_ isEnabled: Bool) {
        if isAllVideoEnabled == isEnabled { return }
        guard let assets = assets else { return }
        for asset in assets {
            if asset.mediaType == .video {
                asset.isEnabled = isEnabled
            }
        }
        isAllVideoEnabled = isEnabled
    }
    
    /// 禁止所有未选中的资源选择
    private func disableAllUnselectedAssets() {
        guard let assets = assets else { return }
        for asset in assets {
            asset.isEnabled = selectedAssets.contains(asset)
        }
        isAllVideoEnabled = false
    }
    
    /// 恢复所有未选中的资源选择
    private func reenableAllUnselectedAssets() {
        guard let assets = assets else { return }
        for asset in assets {
            asset.isEnabled = true
        }
        isAllVideoEnabled = true
    }
    
    /// 判断发布按钮可选状态
    private func updatePostSelectingStatus() {
        self.postButton?.isEnabled = textView.text.count > 0
    }
    
}

// MARK: ------------------ 发布相关 ----------------------
extension PublishViewController {
    
    private func publish() {
        if let text = textView.text {
            NotificationCenter.default.post(name: GlobalNotificationName.publishPost.name,
                                            object: nil,
                                            userInfo: ["assets":    selectedAssets,
                                                       "content":   text])
        }
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UITextViewDelegtae ----------------------
extension PublishViewController: GrowingTextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        textCountLabel.text = "\(textView.text.count)/\(PublishViewController.maxTextCount)"
        updatePostSelectingStatus()
    }

}

// MARK: ------------------ UICollectionViewDelegate ----------------------
extension PublishViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if textView.isFirstResponder {
            textView.resignFirstResponder()
        }
        if collectionView == photoLibraryCollectionView, let asset = assets?[indexPath.item] {
            (!asset.isSelected && !photoLibrarySelectable && asset.isEnabled) ? select(asset) : deselect(asset)
        } else {
            if selectedAssets.count > indexPath.item {
                deselect(selectedAssets[indexPath.item])
            }
        }
        photoLibraryCollectionView.reloadData()
        selectedAssetCollectionView.reloadData()
    }
    
    /// 选中资源
    private func select(_ asset: MTAsset) {
        asset.isSelected = true
        /// 选中逻辑
        if !selectedAssets.contains(asset) {
            selectedAssets.append(asset)
        }
        if photoLibrarySelectable {
            disableAllUnselectedAssets()
        } else if selectedAssets.first?.mediaType != .video {
            setAllVideoEnabled(false)
        }
    }
    
    /// 取消选中资源
    private func deselect(_ asset: MTAsset) {
        asset.isSelected = false
        /// 未选中逻辑
        if selectedAssets.contains(asset), let idx = selectedAssets.firstIndex(of: asset) {
            selectedAssets.remove(at: idx)
        }
        if selectedAssets.count == 0 {
            reenableAllUnselectedAssets()
        }
    }
    
}

// MARK: ------------------ UICollectionViewDataSource ----------------------
extension PublishViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == selectedAssetCollectionView {
            if photoLibrarySelectable {
                return selectedAssets.count
            }
            return selectedAssets.count + 1
        } else {
            return assets?.count ?? 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == selectedAssetCollectionView {
            if indexPath.item == selectedAssets.count {
                guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PublishAddAssetCollectionViewCell.self), for: indexPath) as? PublishAddAssetCollectionViewCell else {
                    return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PublishAddAssetCollectionViewCell.self), for: indexPath)
                }
                return cell
            } else {
                guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PhotoLibarayCollectionViewCell.self), for: indexPath) as? PhotoLibarayCollectionViewCell else {
                    return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PhotoLibarayCollectionViewCell.self), for: indexPath)
                }
                cell.coverImageViewCornerRadius = 5
                cell.asset = selectedAssets[indexPath.item]
                return cell
            }
        } else {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PhotoLibrarySelectableCollectionViewCell.self), for: indexPath) as? PhotoLibrarySelectableCollectionViewCell else {
                return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PhotoLibrarySelectableCollectionViewCell.self), for: indexPath)
            }
            cell.coverImageViewCornerRadius = 5
            cell.asset = assets?[indexPath.item]
            return cell
        }
    }
    
}
